package com.sz.classload;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.atomic.AtomicInteger;

public class PriorityRunnable<E extends Comparable<? super E>>
        implements Runnable,Comparable<PriorityRunnable<E>> {
   private final static AtomicInteger seq = new AtomicInteger();
   private final int seqNum;
   Runnable run;
   private int priority;

    public PriorityRunnable(Runnable run, int priority) {
        seqNum = seq.getAndIncrement();
        this.run = run;
        this.priority = priority;
    }

    @Override
    public int compareTo(@NotNull PriorityRunnable<E> other) {
        int res = 0;
        if (this.priority == other.priority){
            if (other.run != this.run){
                //优先级相同 比较入队顺序
                res = (this.seqNum < other.seqNum ? -1 : 1);
            }
        }else {
            res = this.priority > other.priority ? -1:1;
        }
        return res;
    }

    @Override
    public void run() {
        this.run.run();
    }

    public Runnable getRun() {
        return run;
    }

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }
}
